package com.sx.iptv.task;

import com.sx.iptv.enc.CryptoUtil;
import com.sx.iptv.http.OkHttpExample;
import com.sx.iptv.model.Param;
import lombok.RequiredArgsConstructor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class WatchTask {
    private static final Logger logger = LoggerFactory.getLogger(WatchTask.class);

    private final StringRedisTemplate stringRedisTemplate;
    @Scheduled(cron = "0 0/5 * * * ?") // 每分钟执行一次
    public void watch() {
        String tvUrl = stringRedisTemplate.opsForValue().get("tv_url");

        if (!StringUtils.hasLength(tvUrl)) {
            callDec();
            return;
        }

        if (!isValid(tvUrl)) {
            callDec();
        }
    }

    private void callDec() {
        Param param = OkHttpExample.getParam();
        String url = CryptoUtil.getUrl(param);
        stringRedisTemplate.opsForValue().set("tv_url", url, 1, TimeUnit.DAYS);
    }

    private boolean isValid(String tvUrl) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(tvUrl)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                return true;
            }
            return false;
        } catch (Exception e) {
            logger.error(e.getLocalizedMessage(), e);
            return false;
        } finally {
            IOUtils.closeQuietly(response);
        }
    }
}

